package cn.iocoder.yudao.module.system.service.collate;

import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.system.config.collate.CollateConfig;
import cn.iocoder.yudao.module.system.controller.admin.collate.vo.CollateVo;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Validated
@Slf4j
public class CollateServiceImpl implements CollateService {

    @Autowired
    CollateConfig collateConfig;

    @Override
    public Map<String, Object> toDataText(CollateVo collateVo) {
        Map<String,Object> map = new HashMap<>();
        JSONObject paramJson = new JSONObject();
        paramJson.put("mode", collateVo.getMode());
        paramJson.put("text", collateVo.getText());
        String token = getToken();
        if (StringUtils.isNotEmpty(token)) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(collateConfig.getCollateUrl());
                httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
                httpPost.addHeader("authorization", token);
                StringEntity entity = new StringEntity(paramJson.toJSONString(), StandardCharsets.UTF_8);
                httpPost.setEntity(entity);

                CloseableHttpResponse response = httpClient.execute(httpPost);
                HttpEntity responseEntity = response.getEntity();
                String result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                JSONObject resultJSONObject = JSONObject.parseObject(result);
                String data = resultJSONObject.getString("data");
                map.put("data", data);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                return map;
            }
        }
        return map;
    }

    public String getToken(){
        com.alibaba.fastjson.JSONObject paramJson = new com.alibaba.fastjson.JSONObject();
        paramJson.put("username", collateConfig.getUsername());
        paramJson.put("code", collateConfig.getCode());
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(collateConfig.getLoginUrl());
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity entity = new StringEntity(paramJson.toJSONString(), StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            com.alibaba.fastjson.JSONObject resultJSONObject = JSONObject.parseObject(result);
            return resultJSONObject.getString("token");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    @Autowired
//    private CollateConfig collateConfig;
//
//
//    @Autowired
//    private RestTemplate restTemplate;

//    @Override
//    public Map<String, Object> toDataText(CollateVo collateVo) {
//        Map<String, Object> map = new HashMap<>();
//
//        String token = toLogonGetToken(collateConfig.getLoginUrl());
//        int start = 0;
//        if (collateVo.getPageSize()!=null && collateVo.getPageSize() > 0) {
//            start = collateVo.getPageSize() * (collateVo.getPageNum() - 1);
//        }
//
//
//        // 定义接口请求路径
//        //String url = "http://xiaosi.trs.cn/ckm-open/api/open/JsonBody/ckm-collate/proxy/collate/text";
//
//        // 定义请求头
//        HttpHeaders headers = new HttpHeaders();
//        // 添加请求参数格式
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        // 添加个人token
//        headers.set("Authorization", token);
//        /*
//         对于 JsonBody 类型，请求参数要以 JSON字符串 的形式传入
//         若项目中存在请求参数定义类，可直接将该类的实例对象以 JSON 字符串的形式传入
//         若不存在，建议定义一个 JSON类来编写请求参数
//       */
//
//        // 定义请求参数
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.set("mode", collateVo.getMode());
//        jsonObject.set("text", collateVo.getText());
//
//
//        String bodyStr = JSONUtil.toJsonStr(jsonObject);
//
//        // 请求拼接
//        HttpEntity<String> requestParams = new HttpEntity<>(bodyStr, headers);
//
//        // 调用指定接口，以 JSONObject 获取调用结果
//        try {
//            // PostForObject：只提取 ResponseBody
//            JSONObject result = restTemplate.postForObject(collateConfig.getCollateUrl(), requestParams, JSONObject.class);
//            List<Map<String, Object>> mapList = (List<Map<String, Object>>) result.get("data");
//            map.put("totals", mapList.size());
//            //语句进行转化
//            // 正确语句
//            toCollateTure(mapList);
//            if (collateVo.getPageSize()!=null && collateVo.getPageSize() > 0) {
//                int end = start + collateVo.getPageSize();
//                mapList = mapList.subList(start, Math.min(end, mapList.size()));
//            }
//            map.put("rows", mapList);
//
////            System.out.println(result);
//        } catch (RestClientException e) {
//            System.out.println(e.getMessage());
//        }
//        return map;
//    }

    private void toCollateTure(List<Map<String, Object>> mapList) {
        for (Map<String, Object> map : mapList) {
            map.put("trueSentence", map.get("sentence").toString().replace(map.get("errorWord").toString(), map.get("collateWord").toString()));
        }

    }

//    private String toLogonGetToken(String url) {
//        // 定义接口请求路径
//
//        // 定义请求头
//        HttpHeaders headers = new HttpHeaders();
//        // 添加请求参数格式
//        headers.setContentType(MediaType.APPLICATION_JSON);
//
//        /*
//         对于 JsonBody 类型，请求参数要以 JSON字符串 的形式传入
//         若项目中存在请求参数定义类，可直接将该类的实例对象以 JSON 字符串的形式传入
//         若不存在，建议定义一个 JSON类来编写请求参数
//       */
//        // 定义请求参数
//        JSONObject jsonObject = new JSONObject();
////        jsonObject.set("username", collateConfig.getUsername());
////        jsonObject.set("code", collateConfig.getCode());
//        jsonObject.set("username", "admin");
//        jsonObject.set("code", "$2a$10$UvHhfGDqufpO07tTTapQOey/mG7OyjuKca.oqq3DFxwDLjUgYxY52");
//
//        String bodyStr = JSONUtil.toJsonStr(jsonObject);
//
//        // 请求拼接
//        HttpEntity<String> requestParams = new HttpEntity<>(bodyStr, headers);
//
//        // 调用指定接口，以 JSONObject 获取调用结果
//        try {
//            // PostForObject：只提取 ResponseBody
//            JSONObject result = restTemplate.postForObject(url, requestParams, JSONObject.class);
//            System.out.println(result);
//            return result.get("token").toString();
//        } catch (RestClientException e) {
//            System.out.println(e.getMessage());
//        }
//        return null;
//    }

    public static void main(String[] args) {
        CollateServiceImpl collateService = new CollateServiceImpl();
//        System.out.println("collateService.loginUrl = " + collateService.loginUrl);
//        String logonGetToken = collateService.toLogonGetToken("http://10.101.221.237/ckm-open/api/login");
//        System.out.println("logonGetToken = " + logonGetToken);
        CollateVo collateVo = new CollateVo();
        collateVo.setMode(0);
        collateVo.setText("第五届联合国环境大会第二阶段会议在肯尼亚首都蒙巴萨举行。3月1日，生态环境部部长黄润秋率团线上参会，并在多边幻境协定领导者对话会上视频发言。2022年3月3，联合国环境规划署(ULEP)在总部所在地内罗毕举行了纪念成立50周年特别会议，环境部长黄润秋以视频方式出席会议并发言。");
        Map<String, Object> dataText = collateService.toDataText(collateVo);
        System.out.println(dataText);
    }
}
